package middleware

import (
	"go-pan/internal/log"
	"go-pan/internal/utils"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// AccessLogMiddleware 访问日志中间件
// 记录：IP、耗时、状态码、请求路径、请求方法、User-Agent等
func AccessLogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery
		method := c.Request.Method

		// 执行请求
		c.Next()

		// 计算耗时
		latency := time.Since(start)

		// 获取客户端IP
		clientIP := c.ClientIP()

		// 获取用户信息（如果有）
		userID := int64(0)
		username := ""
		if userInfo, ok := utils.GetUserInfo(c); ok && userInfo != nil {
			userID = userInfo.ID
			username = userInfo.Username
		}

		// 构建日志字段
		fields := []zap.Field{
			zap.String("method", method),
			zap.String("path", path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("latency", latency),
			zap.String("ip", clientIP),
			zap.String("user_agent", c.Request.UserAgent()),
		}

		if raw != "" {
			fields = append(fields, zap.String("query", raw))
		}

		if userID > 0 {
			fields = append(fields, zap.Int64("user_id", userID))
		}
		if username != "" {
			fields = append(fields, zap.String("username", username))
		}

		// 如果有错误信息，记录错误
		if len(c.Errors) > 0 {
			fields = append(fields, zap.Strings("errors", c.Errors.Errors()))
		}

		// 根据状态码选择日志级别
		status := c.Writer.Status()
		switch {
		case status >= 500:
			log.AccessLogger.Error("request failed", fields...)
		case status >= 400:
			log.AccessLogger.Warn("request error", fields...)
		default:
			log.AccessLogger.Info("request completed", fields...)
		}
	}
}
